package com.pluto.cloud.example.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pluto.cloud.example.dao.UserDao;
import com.pluto.cloud.example.domain.User;
import com.pluto.cloud.example.service.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/16.
 */
@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private DiscoveryClient client;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserDao userDao;

    @RequestMapping("/getAllUsers")
    public List<User> getAllUsers(HttpSession session) {
        List<User> result = userMapper.findAll();
        ObjectMapper objectMapper = new ObjectMapper();

        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        ServiceInstance instance = client.getLocalServiceInstance();
        LoggerFactory.getLogger(UserController.class).info(session.getId());
        logger.info("/getAllUsers, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + jsonStr);
        return result;
    }



    @RequestMapping("/findUserById/{id}")
    public User findUserById(@PathVariable("id") int id, HttpSession session) {
        User result = userDao.findUserById(id);
        ObjectMapper objectMapper = new ObjectMapper();

        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        ServiceInstance instance = client.getLocalServiceInstance();
        LoggerFactory.getLogger(UserController.class).info(session.getId());
        logger.info("/findUserById, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + jsonStr);
        return result;
    }
}
